<?php
namespace App\Http\Controllers\MLM;

use App\Http\Controllers\Controller;
use App\Jobs\MLMRelateJob;
use App\Libraries\Decorator\Image\CoverDecorator;
use App\Libraries\Decorator\Tool\IsEndDecorator;
use App\Libraries\Tools\ConstVar;
use App\Models\MLM\MLM;
use App\Models\MLM\MLMBalance;
use App\Models\MLM\MLMBalanceLog;
use App\Models\User\SMS;
use App\Models\User\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class MLMController extends Controller{

    protected $MLM;
    protected $coverDecorator;
    protected $isEndDecorator;

    public function __construct(MLM $MLM, CoverDecorator $coverDecorator, IsEndDecorator $isEndDecorator){
        $this->MLM = $MLM;
        $this->coverDecorator = $coverDecorator;
        $this->isEndDecorator = $isEndDecorator;
    }

    /**
     * MLM建立关系
     * @param Request $request
     * @param SMS $SMS
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function addRelate(Request $request, SMS $SMS, User $user){
        $validator = Validator::make($request->all(), [
            'mobile' => ['regex:/^1[34578][0-9]{9}$/','required'],
            'code' => 'required|size:4',
        ], [
            'mobile.required' => '10001',
            'mobile.regex' => '10002',
            'code.required' => '10001',
            'code.size' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if($request['mobile'] == Auth::user()->mobile){
            return $this->sendFailResponse(400,40001);
        }

        $code = $SMS->checkCode($request['mobile'], $request['code']);
        if(!$code){
            return $this->sendFailResponse(400,40002);
        }
        $code->status = 1;
        $code->save();
        $user = $user->getUserObjectByOpenIdOrMobile($request['mobile']);
        if(empty($user)){
            $user = new User();
            $user->mobile = $request['mobile'];
            $user->save();
        }
        $exist = $this->MLM->where('user_id', $user->user_id)
            ->orWhere('l_parent_id', $user->user_id)
            ->orWhere('m_parent_id', $user->user_id)
            ->orWhere('s_parent_id', $user->user_id)
            ->first();
        if($exist){
            return $this->sendFailResponse(400,40001);
        }
        dispatch(new MLMRelateJob(Auth::id(),$user->user_id ));
        return $this->sendSuccessResponse([]);
    }

    /**
     * 邀请建立关系
     * @param Request $request
     * @param SMS $SMS
     * @param User $user
     * @return \Illuminate\Http\JsonResponse
     */
    public function invite(Request $request, SMS $SMS, User $user){
        $validator = Validator::make($request->all(), [
            'mobile' => ['regex:/^1[34578][0-9]{9}$/','required'],
            'code' => 'required|size:4',
            'invite_id' => 'required|integer',
        ], [
            'mobile.required' => '10001',
            'mobile.regex' => '10002',
            'code.required' => '10001',
            'code.size' => '10002',
            'invite_id.required' => '10001',
            'invite_id.size' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $code = $SMS->checkCode($request['mobile'], $request['code']);
        if(!$code){
            return $this->sendFailResponse(400,40002);
        }
        $code->status = 1;
        $code->save();
        $inviter = $user->where('user_id', $request['invite_id'])->where('status', 1)->first();
        if(empty($inviter)){
            return $this->sendFailResponse(400,40400);
        }

        $user = $user->getUserObjectByOpenIdOrMobile($request['mobile']);
        if(empty($user)){
            $user = new User();
            $user->mobile = $request['mobile'];
            $user->save();
        }
        if($user->user_id == $inviter->user_id){
            return $this->sendFailResponse(400,40001);
        }
        $exist = $this->MLM->where('user_id', $user->user_id)
            ->orWhere('l_parent_id', $user->user_id)
            ->orWhere('m_parent_id', $user->user_id)
            ->orWhere('s_parent_id', $user->user_id)
            ->first();
        if($exist){
            return $this->sendFailResponse(400,40001);
        }
        dispatch(new MLMRelateJob($inviter->user_id, $user->user_id));
        return $this->sendSuccessResponse([]);
    }

    /**
     * MLM关系
     * @return \Illuminate\Http\JsonResponse
     */
    public function relates(){
        if(!Auth::user()->is_auth){
            return $this->sendFailResponse(400, 40101);
        }
        $today = strtotime(date('Y-m-d', time()));
        $data['s_children'] = $this->MLM->where('s_parent_id', Auth::id())->count();
        $data['m_children'] = $this->MLM->where('m_parent_id', Auth::id())->count();
        $data['l_children'] = $this->MLM->where('l_parent_id', Auth::id())->count();
        $data['new_s_children'] = $this->MLM->where('s_parent_id', Auth::id())->where('created_at', '>=', $today)->count();
        $data['new_m_children'] = $this->MLM->where('m_parent_id', Auth::id())->where('created_at', '>=', $today)->count();
        $data['new_l_children'] = $this->MLM->where('l_parent_id', Auth::id())->where('created_at', '>=', $today)->count();
        $data['total_children'] = $data['s_children'] + $data['m_children'] + $data['l_children'];
        $data['new_children'] = $data['new_s_children'] + $data['new_m_children'] + $data['new_l_children'];
        return $this->sendSuccessResponse($data);
    }

    /**
     * 下级数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function children(Request $request){
        $validator = Validator::make($request->all(), [
            'page' => 'required|integer',
            'size' => 'required|integer',
            'level' => 'required|in:s,m,l',
        ], [
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
            'level.required' => '10001',
            'level.in' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if(Auth::user()->vip_level != 2){
            return $this->sendFailResponse(400, 40101);
        }
        $this->MLM->addDecorator($this->coverDecorator);
        $this->MLM->addDecorator($this->isEndDecorator);
        $data = $this->MLM->getChildren(Auth::id(), $request['level'], $request['page'], $request['size']);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 利润
     * @param MLMBalance $MLMBalance
     * @param MLMBalanceLog $MLMBalanceLog
     * @return \Illuminate\Http\JsonResponse
     */
    public function profit(MLMBalance $MLMBalance, MLMBalanceLog $MLMBalanceLog){
        $balance = $MLMBalance->where('user_id', Auth::id())->first();
        $data['today_balance'] = $MLMBalanceLog->where('to_id', Auth::id())
            ->where('type', '<>', ConstVar::$MLM_BALANCE_LOG_TYPE_WITHDRAW)
            ->where('created_at', '>=', Carbon::today()->timestamp)
            ->sum('balance');
        $data['remain_balance'] = $balance->balance??0;
        $data['total_balance'] = $balance->total_balance??0;
        $MLMBalanceLog->addDecorator(new CoverDecorator());
        $MLMBalanceLog->addDecorator(new IsEndDecorator());
        $data['logs'] = $MLMBalanceLog->logs(Auth::id(), 1, 3);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 流水
     * @param Request $request
     * @param MLMBalanceLog $MLMBalanceLog
     * @return \Illuminate\Http\JsonResponse
     */
    public function balanceLogs(Request $request, MLMBalanceLog $MLMBalanceLog){
        $validator = Validator::make($request->all(), [
            'page' => 'required|integer',
            'size' => 'required|integer',
        ], [
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $MLMBalanceLog->addDecorator(new CoverDecorator());
        $MLMBalanceLog->addDecorator(new IsEndDecorator());
        $data = $MLMBalanceLog->logs(Auth::id(), $request['page'], $request['size']);
        return $this->sendSuccessResponse($data);
    }

}